package mnstudent.global;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Administrator
 */
public class DriversHandler extends DefaultHandler {

    private List<Driver> drivers;
    private Driver driver;

    private boolean aName;
    private boolean aURL;
    private boolean aDriverName;

    public DriversHandler() {
        drivers = null;
        driver = null;

        aName = false;
        aURL = false;
        aDriverName = false;
    }

    public List<Driver> getDrivers() {
        return drivers;
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if (qName.equalsIgnoreCase("driver")) {
            String id = attributes.getValue("id");
            driver = new Driver();
            driver.setId(Integer.parseInt(id));

            if (drivers == null) {
                drivers = new ArrayList<>();
            }
        } else if (qName.equalsIgnoreCase("name")) {
            aName = true;
        } else if (qName.equalsIgnoreCase("url")) {
            aURL = true;
        } else if (qName.equalsIgnoreCase("drivername")) {
            aDriverName = true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("driver")) {
            drivers.add(driver);
        }
    }

    @Override
    public void characters(char ch[], int start, int lenght) throws SAXException {
        if (aName) {
            driver.setName(new String(ch, start, lenght));
            aName = false;
        } else if (aURL) {
            driver.setURL(new String(ch, start, lenght));
            aURL = false;
        } else if (aDriverName) {
            driver.setDriverName(new String(ch, start, lenght));
            aDriverName = false;
        }
    }
}
